<?php

namespace app\helper;

use App\ATrait\Single;
use app\model\SmsCodeRecord;
use Exception;

class SmsVerifyCode
{

    use Single;

    protected Config $configRe;


    public function __construct()
    {
        $this->configRe = Config::getInstance();
    }


    /**
     * 验证码验证
     *
     * @param string $phone
     * @param string $code
     * @param string $channel
     * @param string $scene
     * @return true
     * @throws Exception
     */
    public function VerifyCode(string $phone, string $code, string $channel, string $scene): bool
    {

        $sql = SmsCodeRecord::query()->where([
            ['phone', $phone],
            ['channel', $channel],
            ['scene', $scene],
            ['code', $code],
        ]);
        $isExists = (clone $sql)->exists();

        if (!$isExists) {
            throw new Exception('请先获取验证码', 500);
        }

        $logInfo = (clone $sql)->latest('created_at')->first()->toArray();

        // 使用状态验证
        if ($logInfo['state']) {
            throw new Exception('验证码已使用', 500);
        }

        // 超时验证 (5分钟超时)
        $validTime = max(1, $this->configRe->Get('verify_code_valid_time', 5));
        if ((time() - strtotime($logInfo['created_at'])) >= ($validTime * 60)) {
            throw new Exception('验证码已过期', 500);
        }

        try {
            // 将本次验证码状态改为已使用
            (clone $sql)->update([
                'state' => 1,
            ]);

            return true;
        } catch (Exception) {
            throw new Exception('请重新获取验证码', 500);
        }

    }

}
